package com.example.enterprisemanager.mvvm.main;

import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.enterprisemanager.BR;
import com.example.enterprisemanager.R;
import com.example.enterprisemanager.base.BaseActivity;
import com.example.enterprisemanager.base.BaseMainFragment;
import com.example.enterprisemanager.databinding.ActivityMainBinding;
import com.example.enterprisemanager.mvvm.ben.User;
import com.example.enterprisemanager.mvvm.fragment.account.login.LoginFragment;
import com.example.enterprisemanager.mvvm.fragment.allocate.AllocateFragment;
import com.example.enterprisemanager.mvvm.fragment.finding.FindingFragment;
import com.example.enterprisemanager.mvvm.fragment.manager.ManagerFragment;
import com.example.enterprisemanager.util.MyDialog;
import com.example.enterprisemanager.util.ToastUtil;

import cn.bmob.v3.BmobUser;
import me.yokeyword.fragmentation.ISupportFragment;
import me.yokeyword.fragmentation.SupportFragment;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel>
        implements NavigationView.OnNavigationItemSelectedListener, BaseMainFragment.OnFragmentOpenDrawerListener
        , LoginFragment.OnLoginSuccessListener {

    public static final String TAG = MainActivity.class.getSimpleName();

    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;

    private TextView mTvName;   // NavigationView上的名字
    private ImageView mImgNav;  // NavigationView上的头像
    LinearLayout llNavHeader;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected Class<MainViewModel> getModelClass() {
        return MainViewModel.class;
    }

    @Override
    protected int getVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void initView() {
        super.initView();

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mBinding.drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//        mDrawer.setDrawerListener(toggle);
        toggle.syncState();

        mBinding.navView.setNavigationItemSelectedListener(this);
        mBinding.navView.setCheckedItem(R.id.nav_manager);

        llNavHeader = (LinearLayout) mBinding.navView.getHeaderView(0);
        mTvName = (TextView) llNavHeader.findViewById(R.id.tv_name);
        mImgNav = (ImageView) llNavHeader.findViewById(R.id.img_nav);

        BaseMainFragment fragment = findFragment(ManagerFragment.class);
        if (fragment == null) {
            loadRootFragment(R.id.fl_container, ManagerFragment.newInstance());
        }
        onOpenDrawer();
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        mViewModel.sendUserData.observe(this, (user) -> {
            if (user == null) {
                mTvName.setText("请登录");
            } else {
                onLoginSuccess(user);
            }
        });

        llNavHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BmobUser.isLogin()) {
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    mBinding.drawerLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            goLogin();
                        }
                    }, 250);
                } else {
                    new MyDialog().show(getString(R.string.str_tip), getString(R.string.str_is_need_login), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mViewModel.loginOut();
                        }
                    }, null, getSupportFragmentManager());

                }

            }
        });
    }

    /**
     * 设置动画，也可以使用setFragmentAnimator()设置
     */
    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        // 设置默认Fragment动画  默认竖向(和安卓5.0以上的动画相同)
        return super.onCreateFragmentAnimator();
    }


    @Override
    public void onBackPressedSupport() {
        if (mBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            ISupportFragment topFragment = getTopFragment();

            // 主页的Fragment
            if (topFragment instanceof BaseMainFragment) {
                mBinding.navView.setCheckedItem(R.id.nav_manager);
            }

            if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
                pop();
            } else {
                if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
                    finish();
                } else {
                    TOUCH_TIME = System.currentTimeMillis();
                    Toast.makeText(this, R.string.press_again_exit, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 打开抽屉
     */
    @Override
    public void onOpenDrawer() {
        if (!mBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            mBinding.drawerLayout.openDrawer(GravityCompat.START);
        }
    }

    @Override
    public boolean onNavigationItemSelected(final MenuItem item) {
        mBinding.drawerLayout.closeDrawer(GravityCompat.START);

        mBinding.drawerLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                int id = item.getItemId();

                final ISupportFragment topFragment = getTopFragment();
                BaseMainFragment myHome = (BaseMainFragment) topFragment;

                if (id == R.id.nav_manager) {

                    ManagerFragment fragment = findFragment(ManagerFragment.class);
                    Bundle newBundle = new Bundle();
                    newBundle.putString("from", "From:" + topFragment.getClass().getSimpleName());
                    fragment.putNewBundle(newBundle);

                    myHome.start(fragment, SupportFragment.SINGLETASK);
                } else if (id == R.id.nav_allocate) {
                    if (!BmobUser.isLogin()) {
                        ToastUtil.show(getApplication(), "请先登录");
                        return;
                    }
                    AllocateFragment fragment = findFragment(AllocateFragment.class);
                    if (fragment == null) {
                        myHome.startWithPopTo(AllocateFragment.newInstance(), ManagerFragment.class, false);
                    } else {
                        // 如果已经在栈内,则以SingleTask模式start
                        myHome.start(fragment, SupportFragment.SINGLETASK);
                    }

                } else if (id == R.id.nav_finding) {
                    if (!BmobUser.isLogin()) {
                        ToastUtil.show(getApplication(), "请先登录");
                        return;
                    }
                    FindingFragment fragment = findFragment(FindingFragment.class);
                    if (fragment == null) {
                        myHome.startWithPopTo(FindingFragment.newInstance(), ManagerFragment.class, false);
                    } else {
                        myHome.popTo(FindingFragment.class, false);
                    }

                } else if (id == R.id.nav_login) {
                    if (!BmobUser.isLogin()) {
                        mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                        mBinding.drawerLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                goLogin();
                            }
                        }, 250);
                    } else {
                        new MyDialog().show(getString(R.string.str_tip), getString(R.string.str_is_need_login), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mViewModel.loginOut();
                            }
                        }, null, getSupportFragmentManager());

                    }
                }
            }
        }, 300);

        return true;
    }

    private void goLogin() {
        start(LoginFragment.newInstance());
    }

    @Override
    public void onLoginSuccess(User account) {
        mTvName.setText(account.getUsername());
        mImgNav.setImageResource(R.drawable.ic_account_circle_white_48dp);
        Toast.makeText(this, R.string.sign_in_success, Toast.LENGTH_SHORT).show();
    }
}
